###############################################################################
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.views.decorators.http import last_modified
from django.template import loader, RequestContext, TemplateDoesNotExist
from django.forms.formsets import formset_factory

###############################################################################
# Things needed from NoPBX
from nopbx.device.models import Device, DeviceGeneralForm, Line, LineForm


###############################################################################
def index(request):
    """
    Listing of all devices
    """
    device_list = Device.objects.all()
    paginator   = Paginator(device_list, 25) # Show 25 results per page

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        devices = paginator.page(page)
    except (EmptyPage, InvalidPage):
        devices = paginator.page(paginator.num_pages)

    return render_to_response("index.html", {"devices": devices})



###############################################################################
def edit(request, id):
    """
    View for editing a single device
    """
    if request.method == "POST":
        form = DeviceGeneralForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        try:
            device = Device.objects.select_related().get(pk = id)
        except Device.DoesNotExist:
            return redirect("/devices/")

        device_form = DeviceGeneralForm(instance=device)
        max_lines   = range(1, device.model.max_lines + 1)


    return render_to_response("edit.html", {
               "device_form": device_form,
               "device": device,
               "max_lines": max_lines,
             },
             RequestContext(request)
           )



###############################################################################
def edit_line(request, device, index):
    """
    AJAX Line handler
    """
#    if not request.is_ajax():
#        # Not an AJAX request, Error out
#        return HttpResponse(status=400)

    # Get the existing data, or create a new line form
    try:
        line = Line.objects.get(device = device, index = index)
    except Line.DoesNotExist:
        line = None

    # Need more processing here.  This should save an existing line, but not add one...
    if request.method == 'POST' and line:
        line_form = LineForm(request.POST, instance = line)
        if line_form.is_valid():
            line_form.save()
    else:
        if line:
            line_form = LineForm(instance=line)
        else:
            line_form = LineForm()

    return render_to_response("edit_line.html", {
               "device_id": device,
               "index": index,
               "line_form": line_form
             },
             RequestContext(request)
           )



###############################################################################
def line_label(request, device, index):
    """
    Return the label of the line for the device specified
    """

    # Not an AJAX request, Error out
    if not request.is_ajax():
        raise Http404

    try:
        line = Line.objects.get(device = device, index = index)
    except Line.DoesNotExist:
        return HttpResponse("(Blank)")

    return HttpResponse(line.label)



###############################################################################
def config_modified(request, mac_address):
    """
    Return the last modified date from the database, and not the current time.
    By default, Polycom phones check to see if the config file has been modified
    and only update and reboot if they have
    """
    try:
        device = Device.objects.get(mac_address = mac_address)
    except Device.DoesNotExist:
        return None

    return device.modified

@last_modified(config_modified)



###############################################################################
def config(request, mac_address):
    """
    Generate the configuration for the device based on the type of device.
    """
    device = get_object_or_404(Device, mac_address = mac_address)

    try:
        return render_to_response('%s/config.xml' % device.model.manufacturer.name.lower(), {'device': device}, mimetype='application/xml')
    except TemplateDoesNotExist:
        raise Http404


